package com.diyunapp.xilinapp.myindent;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.bean.FootMarkBean;
import com.diyunapp.xilinapp.details.GoodsDetailActivity;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.myapi.BuyCarGoodsInfoChageInterface;
import com.diyunapp.xilinapp.selfdefine.StatusBarFragmentActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FootmarkActivity extends StatusBarFragmentActivity {

    @Bind(R.id.edit_zuji)
    TextView editZuji;
    @Bind(R.id.go_back)
    ImageView goBack;
    @Bind(R.id.footmark_list)
    ListView footmarkList;
    @Bind(R.id.footmark_refresh_view)
    SwipeRefreshLayout footmarkRefreshView;
    private LayoutInflater inflater;
    private FootMarkAdapter1 footMarkAdapter1;
    private static SharedPreferences sp;
    private List<FootMarkBean.DateBean> info = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_footmark);
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        ButterKnife.bind(this);
        View headView;
        headView = findViewById(R.id.footmark_menubar_inc);
        super.MenuWidget(headView);
        SharedPreferences sp=getSharedPreferences("Delete",1);
        sp.edit().putBoolean("ifDeletestate",false).commit();
        footMarkAdapter1 = new FootMarkAdapter1(this);
        initfootmarks1();
        footmarkList.setAdapter(footMarkAdapter1);
        footmarkRefreshView.setColorSchemeColors(R.color.domain_orange, R.color.green,
                R.color.blue, R.color.yellow);

        footmarkRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("zhangxiaoxidebug", "myordersSwiperefreshlayout onRefresh...");
                initfootmarks1();            }
        });

    }


    private void initfootmarks1() {
//        String url = "http://xilin.diyunkeji.com/mobile/index.php?act=goods&op=my_zuji&username=junjun";
        String url = "" + MainActivity.url + "act=goods&op=my_zuji&username=" + MainActivity.myLogin.getUsername() + "";
        Log.i("zhangxiaoxidebug", "resultinfo=" + url);

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        footmarkRefreshView.setRefreshing(false);
                        String resultinfo = responseInfo.result;
//                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");

                            if (result == 200) {
                                info.clear();
                                JSONArray listArray = resultObject.optJSONArray("date");
                                for (int i = 0; i < listArray.length(); i++) {
                                    JSONObject recordObject = listArray.optJSONObject(i);
                                    String goods_id = recordObject.optString("goods_id");
                                    String goods_name = recordObject.optString("goods_name");
                                    String goods_promotion_price = recordObject.optString("goods_promotion_price");
                                    String goods_salenum = recordObject.optString("goods_salenum");
                                    String goods_marketprice = recordObject.optString("goods_marketprice");
                                    String goods_image = recordObject.optString("goods_image");
                                    info.add(new FootMarkBean.DateBean(goods_id, goods_name, goods_promotion_price, goods_salenum,
                                            goods_marketprice, goods_image));
                                }
                                footMarkAdapter1.setList(info);
                                footMarkAdapter1.notifyDataSetChanged();

                            } else {
                                toast("当前暂无数据");
                                footmarkRefreshView.setVisibility(View.GONE);
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();
                            footmarkRefreshView.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        footmarkRefreshView.setRefreshing(false);
                        toast("请求失败");
                        footmarkRefreshView.setVisibility(View.GONE);
                    }
                });
    }

    @OnClick({R.id.edit_zuji, R.id.go_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.go_back:
                finish();
                break;
            case R.id.edit_zuji:
//                flage=!flage;
//                footMarkAdapter1.notifyDataSetChanged();
                if (editZuji.getText().toString() == "编辑" || editZuji.getText().toString().equals("编辑")) {
//                    ifDeletestate = true;
                     sp=getSharedPreferences("Delete",1);
                    sp.edit().putBoolean("ifDeletestate",true).commit();
                    footMarkAdapter1.notifyDataSetChanged();
                    editZuji.setText("完成");
                } else if (editZuji.getText().toString() == "完成" || editZuji.getText().toString().equals("完成")) {
                     sp=getSharedPreferences("Delete",1);
                    sp.edit().putBoolean("ifDeletestate",false).commit();
                    footMarkAdapter1.notifyDataSetChanged();
//                    ifDeletestate = false;
                    editZuji.setText("编辑");
                }
                break;
            default:
                break;
        }
    }

    class FootMarkAdapter1 extends BaseAdapter  {
        private List<FootMarkBean.DateBean> info = new ArrayList<FootMarkBean.DateBean>();
        private Context context;
        private BuyCarGoodsInfoChageInterface goodsChangeIf;

        public FootMarkAdapter1(Context context) {
            super();
            this.context = context;
        }

        public void setList(List<FootMarkBean.DateBean> list) {
            this.info = list;
        }

        @Override
        public int getCount() {
            return null == info ? 0 : info.size();
        }

        @Override
        public Object getItem(int position) {
            return null == info ? null : info.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        private ViewHolder viewHolder;

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (null == convertView) {
                convertView = inflater.inflate(R.layout.item_footmark1, null);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            FootMarkBean.DateBean bean1 = info.get(position);
            viewHolder.buycarDeleteallTv.setTag(position);
            boolean  state=false;
            SharedPreferences sp=getSharedPreferences("Delete",1);
             state=sp.getBoolean("ifDeletestate",false);
//            toast(String.valueOf(state));
            if (String.valueOf(state) =="false" ) {
                viewHolder.buycarDeleteallTv.setVisibility(View.GONE);
            } else if(String.valueOf(state) =="true"){
                viewHolder.buycarDeleteallTv.setVisibility(View.VISIBLE);
            }
            final String goods_id = bean1.getGoods_id();

            viewHolder.relativeLayout2.setTag(position);
            viewHolder.introduceGoods.setText(bean1.getGoods_name());
            viewHolder.introducePrice.setText(bean1.getGoods_promotion_price());
            viewHolder.oldPrice.setText(bean1.getGoods_marketprice());
            viewHolder.saleNum.setText(bean1.getGoods_salenum());
            FootMarkBean.DateBean bean = info.get(position);
            String image = bean.getGoods_image();
            Picasso.with(context)
                    .load(image)
                    .resize(200, 200)
                    .centerCrop()
                    .placeholder(R.drawable.list_default)
                    .error(R.drawable.list_default)
                    .into(viewHolder.goodsImage);

            viewHolder.buycarDeleteallTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    initDelete(goods_id);
                    info.clear();
                    initfootmarks1();
                }
            });
            viewHolder.relativeLayout2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    nextAct(GoodsDetailActivity.class);
                    Intent intent = new Intent();
                    intent.setClass(FootmarkActivity.this, GoodsDetailActivity.class);
                    intent.putExtra("GoodId", goods_id);

                    startActivity(intent);
                }
            });
//            footmarkList.setOnItemClickListener(new View.OnItemClickListener() {
//
//            });
            return convertView;
        }

        class ViewHolder {
            @Bind(R.id.goods_image)
            ImageView goodsImage;
            @Bind(R.id.introduce_goods)
            TextView introduceGoods;
            @Bind(R.id.introduce_price)
            TextView introducePrice;
            @Bind(R.id.old_price)
            TextView oldPrice;
            @Bind(R.id.sale_num)
            TextView saleNum;
            @Bind(R.id.buycar_deleteall_tv)
            TextView buycarDeleteallTv;
            @Bind(R.id.relativeLayout2)
            RelativeLayout relativeLayout2;
            ViewHolder(View view) {
                ButterKnife.bind(this, view);
                oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            }
        }


    }

    public void initDelete(String id) {
        String url = ""+MainActivity.url+"act=goods&op=del_zuji" +
                "&username="+MainActivity.myLogin.getUsername()+"&goods_id="+id+"";
        Log.i("zhangxiaoxidebug", "url=" + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
//                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            String  done = resultObject.optString("done");
                            String msg = resultObject.optString("msg");
                            toast(msg);

                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        toast("请求失败");
                    }
                });

    }

}

